package dba.example.entities;

import javax.persistence.Entity
import javax.persistence.GeneratedValue
import javax.persistence.Id
import javax.persistence.PrePersist
import javax.persistence.PreUpdate
import javax.validation.constraints.NotNull
import javax.validation.constraints.Size
import scala.beans.BeanProperty
import org.hibernate.annotations.Cache
import org.hibernate.annotations.CacheConcurrencyStrategy

object Company {

  def apply() = new Company()

  def apply(id: Integer) = {
    val company = new Company()
    company.id = id;
    company
  }
  
  def apply(name: String) = {
    val company = new Company()
    company.name = name
    company
  }

}

@Entity
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
class Company extends AbstractEntity {

  @Id
  @GeneratedValue
  @BeanProperty
  var id: Integer = null;

  @NotNull
  @Size(max = 100)
  @BeanProperty
  var name: String = null;

  @BeanProperty
  var nameSort: String = null;

  /**
   * This is automatically called before the record is inserted and updated
   */
  @PrePersist
  @PreUpdate
  def updateSortColumns() {
    nameSort = if (name == null) null else name.toLowerCase();
  }

  override def toString() = s"[id = $id, name = $name]"

}
